package org.example.network.demo2.server;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.Charset;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author Gong.Yang
 */
@Slf4j
@ChannelHandler.Sharable    //公用handler 需要考虑线程安全问题
public class ServerInboundHandler extends ChannelInboundHandlerAdapter {
    AtomicInteger count = new AtomicInteger();

    /**
     * 管道连接上 pipeline初始化完成回调
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("ServerInboundHandler channelActive remoteAddress:{}", ctx.channel().remoteAddress());
        super.channelActive(ctx);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof ByteBuf byteBuf) {
            byte[] bytes = new byte[byteBuf.readableBytes()];
            byteBuf.readBytes(bytes);
            String content = new String(bytes, Charset.defaultCharset());
            log.info("【读事件】count->{}, content:{}", count.incrementAndGet(), content);
        }
        super.channelRead(ctx, msg);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ByteBuf buffer = ctx.alloc().buffer();
        buffer.writeBytes("hello client , i am server".getBytes());
        ctx.writeAndFlush(buffer);
        super.channelReadComplete(ctx);
    }
}
